package com.sztle.admodule.handler;

import android.app.Activity;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationExpressRenderListener;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationAdEcpmInfo;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationBaseManager;
import com.bytedance.sdk.openadsdk.mediation.manager.MediationNativeManager;
import com.sztle.admodule.GmAdManager;
import com.sztle.admodule.IShowListener;
import com.sztle.admodule.bean.AdConfigInfo;
import com.sztle.admodule.bean.RequestAdEntity;
import com.sztle.admodule.outstatus.AppStatusProcessor;
import com.sztle.admodule.control.manager.ControlManager;
import com.sztle.admodule.myutils.AdLogUtils;
import com.sztle.admodule.myutils.GlobalAppUtils;
import com.sztle.admodule.myutils.UIUtils;

import java.util.LinkedList;
import java.util.List;

public class NativeHandler {
    private static final String TAG = "NativeHandler";
    private static LinkedList<TTFeedAd> sCanUseNativeList = new LinkedList<>();
    private static boolean isLoading = false;

    private static String getCode(){
        AdConfigInfo adConfigInfo = ControlManager.getAdConfigInfo();
        if(adConfigInfo != null && !TextUtils.isEmpty(adConfigInfo.nativeId.trim())){
            return adConfigInfo.nativeId;
        }
        return AppStatusProcessor.getAppParam().nativeAdId;
    }

    public static void loadAndShow(Activity activity, FrameLayout adContainer, IShowListener showListener) {
        if (adContainer == null || activity == null) {
            return;
        }
        if(!GmAdManager.isUseAdExp()){
            return;
        }
        if (sCanUseNativeList.size() > 0) {
            show(adContainer,showListener);
            return;
        }
        if(isLoading){
            if(showListener != null){
                showListener.onJustEnd(false);
            }
            return;
        }
        /** 1、创建AdSlot对象 */
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(getCode())
                .setImageAcceptedSize(UIUtils.getScreenWidthInPx(GlobalAppUtils.getApp()), UIUtils.dp2px(GlobalAppUtils.getApp(), 340)) // 单位px
                .setAdCount(2) // 请求广告数量为1到3条 （优先采用平台配置的数量）
                .build();

        /** 2、创建TTAdNative对象 */
        TTAdNative adNativeLoader = GmAdManager.get().createAdNative(activity);

        /** 3、加载广告 */
        GmAdManager.enterRequestAdQueue(new RequestAdEntity(RequestAdEntity.TYPE_AD_NATIVE));
        isLoading = true;
        adNativeLoader.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() {
            @Override
            public void onError(int i, String s) {
                isLoading = false;
                AdLogUtils.Log(TAG, "onError = " + s);
                if(showListener != null){
                    showListener.onAdLoadEnd(false);
                }
            }

            @Override
            public void onFeedAdLoad(List<TTFeedAd> list) {
                isLoading = false;
                AdLogUtils.Log(TAG, "onFeedAdLoad");
                if(showListener != null){
                    showListener.onAdLoadEnd(true);
                }
                sCanUseNativeList.clear();
                sCanUseNativeList.addAll(list);
                show(adContainer,showListener);
            }
        });
    }

    private static void show(FrameLayout adContainer,IShowListener showListener) {
        if (adContainer == null || sCanUseNativeList.isEmpty()) {
            return;
        }
        if(!GmAdManager.isUseAdExp()){
            return;
        }
       final TTFeedAd current = sCanUseNativeList.poll();
        current.uploadDislikeEvent("mediation_dislike_event");
        /** 5、展示广告 */
        MediationNativeManager manager = current.getMediationManager();

        if (manager != null) {
            if (manager.isExpress()) { // --- 模板feed流广告
                current.setExpressRenderListener(new MediationExpressRenderListener() {

                    @Override
                    public void onRenderSuccess(View view, float v, float v1, boolean b) {
                        renderToContainer(adContainer, current);
                    }

                    @Override
                    public void onRenderFail(View view, String s, int i) {
                        AdLogUtils.Log(TAG, "onRenderFail = " + s);
                    }

                    @Override
                    public void onAdClick() {
                        AdLogUtils.Log(TAG, "onAdClick ");
                    }

                    @Override
                    public void onAdShow() {
                        if(showListener != null){
                            showListener.onAdShow(getEcpm(current));
                        }
                        AdLogUtils.Log(TAG, "onAdShow ");
                        showEcpmInfo(current);
                    }
                });
                current.render(); // 调用render方法进行渲染，在onRenderSuccess中展示广告
            } else {
                //自渲染为空先
            }
        }
    }

    private static void renderToContainer(FrameLayout adContainer, TTFeedAd curFeedAd) {
        if (adContainer == null || curFeedAd == null) {
            return;
        }

        if (adContainer.getVisibility() != View.VISIBLE) {
            adContainer.setVisibility(View.VISIBLE);
        }

        View expressFeedView = curFeedAd.getAdView(); // *** 注意不要使用onRenderSuccess参数中的view ***
        UIUtils.removeFromParent(expressFeedView);
        adContainer.removeAllViews();
        adContainer.addView(expressFeedView);
    }

    private static String getEcpm(TTFeedAd feedAd) {
        if (feedAd == null) {
            return "";
        }
        MediationBaseManager mediationManager = feedAd.getMediationManager();
        if (mediationManager != null) {
            MediationAdEcpmInfo showEcpm = mediationManager.getShowEcpm();
            return showEcpm.getEcpm();
        }
        return "";
    }

    private static void showEcpmInfo(TTFeedAd feedAd) {
        if ( feedAd == null) {
            return;
        }
        MediationBaseManager mediationManager = feedAd.getMediationManager();
        if (mediationManager != null) {
            MediationAdEcpmInfo showEcpm = mediationManager.getShowEcpm();
            if (showEcpm != null) {
                logEcpmInfo(showEcpm);
            }
        }
    }

    private static void logEcpmInfo(MediationAdEcpmInfo item) {
        AdLogUtils.Log(TAG, "EcpmInfo: \n" +
                "SdkName: " + item.getSdkName() + ",\n" +
                "CustomSdkName: " + item.getCustomSdkName() + ",\n" +
                "SlotId: " + item.getSlotId() + ",\n" +
                // 单位：分
                "Ecpm: " + item.getEcpm() + ",\n" +
                "ReqBiddingType: " + item.getReqBiddingType() + ",\n" +
                "ErrorMsg: " + item.getErrorMsg() + ",\n" +
                "RequestId: " + item.getRequestId() + ",\n" +
                "RitType: " + item.getRitType() + ",\n" +
                "AbTestId: " + item.getAbTestId() + ",\n" +
                "ScenarioId: " + item.getScenarioId() + ",\n" +
                "SegmentId: " + item.getSegmentId() + ",\n" +
                "Channel: " + item.getChannel() + ",\n" +
                "SubChannel: " + item.getSubChannel() + ",\n" +
                "customData: " + item.getCustomData()
        );
    }
}
